<?php
namespace app\index\controller;

use think\Controller;
use think\Db;
use think\Request;

/**
 *
 */
class Earthdata extends Controller
{

    public function getData()
    {
        $request = Request::instance();
        if ($request->isPost()) {
            $data = $request->except(['name']);
            $handel = trim($data['handel']);
            $equnique = $data['equnique'];
        }
        $exportData = '';
        switch ($handel) {
            case 'as':
                $exportData = $this->asData($equnique);
                break;

            case 'econ':
                $exportData = $this->econData($equnique);
                break;

            case 'envir':
                $exportData = $this->envirData($equnique);
                break;

            case 'gover':
                $exportData = $this->goverData($equnique);
                break;

            case 'peo':
                $exportData = $this->peoData($equnique);
                break;

            case 'td':
                $exportData = $this->tdData($equnique);
                break;

            case 'topo':
                $exportData = $this->asData($equnique);
                break;
            case 'epic':
                $exportData = $this->epicenter($equnique);
                break;
            case 'wheq':
                $exportData = $this->getWorldHis();
                break;
            case 'cheq':
                $exportData = $this->getChinaHis();
                break;
            default:
                $exportData = $this->packData(null);
                break;
        }
        $exportData = json_encode($exportData);
        return $exportData;
    }

    protected function asData($equnique)
    {

    }
    //
    protected function getWorldHis()
    {
        $result = Db::table('world_his_eq')->order('EarthquakeDate')->select();
        //return "cnm";
        return $this->packData($result);
    }
    //中国历史地震
    protected function getChinaHis()
    {
        $map_mag['Magnitude'] = array('gt',5);
        // $map_lon['Longitude'] = array(array('gt',73.65),array('lt',135.06));
        // $map_lat['Latitude'] = array(array('gt',3.86),array('lt',53.56));
        $result = Db::table('china_his_eq')->order('Magnitude')->where($map_mag)->select();
        return $this->packData($result);
    }

    // 震中
    protected function epicenter($equnique)
    {
        $result = Db::table('published_seismic_database')->field("abvProvince as district, EQTTIME as time, LONGITUDE as lon, LATITUDE as lat, MAGNITUDE as magn, Intensity as intensity, DEPTH as depth")->where("ID = '" . $equnique . "'")->select();
        return $this->packData($result);
    }
    protected function econData($equnique)
    {
        // $result = Db::table('published_seismic_database')->field('eqtname, ROUND(GDP/10000, 2) as GDP,ROUND(FST_INDUSTRY/10000, 2) as FST_INDUSTRY, ROUND(SND_INDUSTRY/10000, 2) as SND_INDUSTRY, ROUND(TRD_INDUSTRY/10000, 2) as TRD_INDUSTRY,Economics')->where("ID = '".$equnique."'")->select();
        $result = Db::table('published_seismic_database')->field('eqtname, ROUND(GDP/10000, 2) as GDP,ROUND(FST_INDUSTRY/10000, 2) as FST_INDUSTRY, ROUND(SND_INDUSTRY/10000, 2) as SND_INDUSTRY, ROUND(TRD_INDUSTRY/10000, 2) as TRD_INDUSTRY')->where("ID = '" . $equnique . "'")->select();
        //var_dump($result);
        return $this->packData($result);
    }

    protected function envirData($equnique)
    {
        $result = Db::table('published_seismic_database')->field('eqtname, altitudeL, altitudeAverage,
                        altitudeH, altitudeCenter, topographic')->where("ID = '" . $equnique . "'")->select();
        return $this->packData($result);
    }

    protected function goverData($equnique)
    {

    }

    protected function peoData($equnique)
    {
        $result = Db::table('published_seismic_database')->field('eqtname, ROUND((POP_COUNTRYSIDE+POP_TOWN)/10000, 2) as POP_ALL, ROUND(POP_COUNTRYSIDE/10000, 2) as POP_COUNTRYSIDE, ROUND(POP_TOWN/10000, 2) as POP_TOWN, urbanAverIncome, villageAverIncom, villageNum, townNum,Population')->where("ID = '" . $equnique . "'")->select();
        return $this->packData($result);
    }

    protected function tdData($equnique)
    {
        $province = Db::table('published_seismic_database')
            ->field('province, x_longitude, x_latitude, MAGNITUDE, EQTTIME')
            ->where("ID = '" . $equnique . "'")
            ->buildSql();
        $provinces = Db::field("ps.province, CONCAT_WS('，',ps.neighbor,ps.province) as neighbor, p.x_longitude, p.x_latitude, p.MAGNITUDE, p.EQTTIME")
            ->table('province ps,' . $province . ' p')
            ->where('ps.province = p.province')
            ->select();
        //var_dump($provinces);
        //此处有一个隐患数据库里的分隔符采用的是中文的逗号
        if (count($provinces) > 0) {
            $result = explode('，', $provinces[0]["neighbor"]);
            array_push($result, $provinces[0]["province"]);
            $lat = $provinces[0]["x_latitude"];
            $lon = $provinces[0]["x_longitude"];
            $magn = $provinces[0]["MAGNITUDE"];
            $eqtime = $provinces[0]["EQTTIME"];
            $nearCityData = $this->findNearCityData($result, $lat, $lon);
            $hisEqData = $this->findHisEq($magn, $lat, $lon, $eqtime);
            $countyData = $this->findCounty($lat, $lon);
        } else {
            $nearCityData = null;
            $hisEqData = null;
            $countyData = null;
        }
        $data = [
            'nearCityData' => $nearCityData,
            'hisEqData' => $hisEqData,
            'countyData' => $countyData,
        ];
        return $this->packData($data);
    }
    //地形地貌同环境信息
    /*protected function topoData($city){

    }*/

    protected function packData($data)
    {
        $stutas = $data == '' || $data == null ? 404 : 200;
        return $exportData = [
            'stutas' => $stutas,
            'data' => $data,
        ];
    }
    protected function findNearCityData($pro, $lat, $lon)
    {
        $map = [
            'province' => ['in', $pro],
            'longtitude' => ['<>', ''],
            'latitude' => ['<>', ''],
        ];
        $result = Db::table('base')
            ->field("name,longtitude,latitude,ROUND(area/1000000, 2) as area,ROUND(GDP/10000, 2) as GDP,ROUND((POP_COUNTRYSIDE+POP_TOWN)/10000, 2) as POP_ALL,ROUND(ROUND(6378.138*2*asin(sqrt(pow(sin( (" . $lat . "*pi()/180-latitude*pi()/180)/2),2)+cos(" . $lat . "*pi()/180)*cos(latitude*pi()/180)* pow(sin( (" . $lon . "*pi()/180-longtitude*pi()/180)/2),2)))*1000)/1000) as distence")
            ->where($map)
            ->order('distence')
            ->limit(4)
            ->select();
        return $result;
    }

    protected function findHisEq($magn, $lat, $lon, $eqtime)
    {
        $range = 0;
        $unit = 1000; //单位(千米)
        $minTime = 999999; //最近时间
        $minDistence = 999999; //最近距离
        $maxMagn = 0; //最大震级
        $exportLength = 0; //记录长度
        $_onekey = '';
        $_twokey = '';
        $_thrkey = ''; //记录key值
        $exportData = array();
        $oneSection = 5.0;
        $twoSection = 6.0;
        $hisOne = '';
        $hisSec = '';
        $hisThr = '';

        $exclude = array();
        $range = $this->getRange($magn);
        $map = "ROUND(6378.138*2*asin(sqrt(pow(sin( (" . $lat . "*pi()/180-Latitude*pi()/180)/2),2)+cos(" . $lat . "*pi()/180)*cos(Latitude*pi()/180)* pow(sin( (" . $lon . "*pi()/180-Longitude*pi()/180)/2),2)))*1000) <= " . $range;

        $packData = Db::table('hisedisaster')
            ->field("OBJECTID,EarthquakeDate, Macro_epicenter, Magnitude, CrackDegree, Death, Area, DirectEconomicLoss, Latitude, Longitude")
            ->where($map)
            ->select();
        return $packData;
        //return $packData;
        $minTime = 999999; //最近时间，只计算了年
        //$minDistence = 999999; //最近距离
        $maxMagn = 0; //最大震级
        //找出最大震级
        foreach ($packData as $key => $value) {
            if ($value["Magnitude"] > $maxMagn) {
                $maxMagn = $value["Magnitude"];
                $_onekey = $key;
                $hisOne = $packData[$_onekey];
            }
        }
        //找出时间最近，震级大于5级的最大震级，排除第一条，
        $maxMagn = 0; //重置
        foreach ($packData as $key => $value) {
            $_time = $this->getYear($value['EarthquakeDate']);
            if ($value["Magnitude"] > $maxMagn && $key != $_onekey && $value["Magnitude"] > $oneSection && $_time < $minTime) {
                $maxMagn = $value["Magnitude"];
                $minTime = $_time;
                $_twokey = $key;
                $hisSec = $packData[$_twokey];
            }
        }
        //找出时间最近，震级大于6级的最大震级，排除第一、二条，
        $maxMagn = 0; //重置
        $minTime = 999999;
        foreach ($packData as $key => $value) {
            $_time = $this->getYear($value['EarthquakeDate']);
            if ($value["Magnitude"] > $maxMagn && $key != $_onekey && $key != $_twokey && $value["Magnitude"] > $twoSection && $_time < $minTime) {
                $maxMagn = $value["Magnitude"];
                $minTime = $_time;
                $_thrkey = $key;
                $hisThr = $packData[$_thrkey];
            }
        }

        /*var_dump($hisOne);
        var_dump($hisTwo);
        var_dump($hisThr);*/
        $exportData['hisOne'] = $hisOne;
        $exportData['hisSec'] = $hisSec;
        $exportData['hisThr'] = $hisThr;
        return $exportData;
    }
    protected function getRange($magn)
    {
        $unit = 1000; //单位(千米)
        $range = 0;
        if (0 < $magn && $magn <= 5.0) {
            $range = 20 * $unit;
        } else if ($magn > 5.0 && $magn <= 5.9) {
            $range = 40 * $unit;
        } else if ($magn > 5.9 && $magn <= 6.9) {
            $range = 100 * $unit;
        } else if ($magn > 6.9 && $magn <= 7.9) {
            $range = 200 * $unit;
        } else if ($magn > 7.9) {
            $range = 400 * $unit;
        }
        return $range;
    }
    protected function findCounty($lat, $lon)
    {
        $unit = 1000; //单位(千米)
        $range = 300 * $unit;
        $map = "name  like  '%县' AND  ROUND(6378.138*2*asin(sqrt(pow(sin( (" . $lat . "*pi()/180-latitude*pi()/180)/2),2)+cos(" . $lat . "*pi()/180)*cos(latitude*pi()/180)* pow(sin( (" . $lon . "*pi()/180-longtitude*pi()/180)/2),2)))*1000)  <=  " . $range;
        //return $map;
        $result = Db::table('base')->field('distinct(name)')->where($map)->select();
        return $result;
    }
    protected function getDistence($Data, $lat, $lon, $dunit = 1, $decimal = 2)
    {

        $EARTH_RADIUS = 6370.996; // 地球半径系数
        $PI = 3.1415926;

        $radLatS = $lat * $PI / 180.0;
        $radLatE = $Data["Latitude"] * $PI / 180.0;

        $radLonS = $lon * $PI / 180.0;
        $radLonE = $Data["Longitude"] * $PI / 180.0;

        $a = $radLatS - $radLatE;
        $b = $radLonS - $radLonE;

        $distence = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLatE) * cos($radLatE) * pow(sin($b / 2), 2)));
        $distence = $distence * $EARTH_RADIUS * 1000;

        if ($dunit == 2) {
            $distence = $distence / 1000;
        }

        return round($distence, $decimal);
    }

    protected function getYear($time)
    {
        $strType = is_numeric($time);

        if ($strType) {
            return $time;
        } else {
            $str = '[-]';
            $type = preg_match($str, $time);
            if ($type) {
                return explode('-', $time)[0];
            }
        }

    }
}
